from __future__ import annotations
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.views import View
from django.views.generic import ListView, TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator
import json
import requests
from datetime import datetime
from typing import Optional, List, Dict, Any, Union, TypeVar, cast, TYPE_CHECKING, ClassVar, Tuple, Iterator, Set
from django.db.models.query import QuerySet, RawQuerySet
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.conf import settings

# 添加 DRF 相关导入
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated

from .models import MapLocation, MapRoute, TencentMapConfig, MapSearchHistory
from .serializers import MapLocationSerializer
from .config import TENCENT_MAP_API_KEY
from rest_framework.decorators import action

# 简化模型管理器类型提示
if TYPE_CHECKING:
    from django.db.models.manager import Manager
    objects: Manager

# 为模型类添加类型提示
if TYPE_CHECKING:
    from .models import MapLocation as MapLocationModel
    from .models import MapRoute as MapRouteModel
    from .models import TencentMapConfig as TencentMapConfigModel
    from .models import MapSearchHistory as MapSearchHistoryModel
    from django.db.models.manager import Manager
    
    class MapLocationType(MapLocationModel):
        objects: Manager
        
        def __init__(self) -> None:
            super().__init__()
            self.name: str
            self.address: str
            self.category: str
            self.is_active: bool
            self.created_at: datetime
    
    class MapRouteType(MapRouteModel):
        objects: Manager
        
        def __init__(self) -> None:
            super().__init__()
            self.travel_mode: str
            self.is_favorite: bool
            self.created_at: datetime
    
    class TencentMapConfigType(TencentMapConfigModel):
        objects: Manager
        
        def __init__(self) -> None:
            super().__init__()
            self.api_key: str
            self.is_active: bool
            self.used_quota: int
            self.daily_quota: int
        def reset_daily_quota(self) -> None: ...
        def save(self, *args: Any, **kwargs: Any) -> None: ...
    
    class MapSearchHistoryType(MapSearchHistoryModel):
        objects: Manager
        
        def __init__(self) -> None:
            super().__init__()
            self.user: Any
            self.search_keyword: str
            self.search_location: str
            self.result_count: int
            self.search_time: datetime
            
    # 类型别名，用于类型检查
    MapLocation = MapLocationType
    MapRoute = MapRouteType
    TencentMapConfig = TencentMapConfigType
    MapSearchHistory = MapSearchHistoryType
else:
    from .models import MapLocation, MapRoute, TencentMapConfig, MapSearchHistory


class MapLocationListView(LoginRequiredMixin, ListView):
    """
    地图位置列表视图
    """
    model = MapLocation
    template_name = 'tencent_map/location_list.html'
    context_object_name = 'locations'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = MapLocation.objects.filter(is_active=True)
        category = self.request.GET.get('category')
        search = self.request.GET.get('search')
        
        if category:
            queryset = queryset.filter(category=category)
        if search:
            queryset = queryset.filter(
                name__icontains=search
            ) | queryset.filter(
                address__icontains=search
            )
        
        return queryset.order_by('-created_at')


class MapRouteListView(LoginRequiredMixin, ListView):
    """
    地图路线列表视图
    """
    model = MapRoute
    template_name = 'tencent_map/route_list.html'
    context_object_name = 'routes'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = MapRoute.objects.all()
        travel_mode = self.request.GET.get('travel_mode')
        is_favorite = self.request.GET.get('is_favorite')
        
        if travel_mode:
            queryset = queryset.filter(travel_mode=travel_mode)
        if is_favorite == 'true':
            queryset = queryset.filter(is_favorite=True)
        
        return queryset.order_by('-created_at')


@method_decorator(csrf_exempt, name='dispatch')
class MapSearchView(LoginRequiredMixin, View):
    """
    地图搜索API视图（需要登录）
    """
    
    def post(self, request):
        try:
            data = json.loads(request.body)
            keyword = data.get('keyword', '')
            location = data.get('location', '')
            
            if not keyword:
                return JsonResponse({
                    'success': False,
                    'message': '搜索关键词不能为空'
                })
            
            # 获取激活的腾讯地图API配置
            config = TencentMapConfig.objects.filter(is_active=True).first()
            if not config:
                return JsonResponse({
                    'success': False,
                    'message': '没有激活的地图API配置'
                })
            
            # 检查配额
            config.reset_daily_quota()
            if config.used_quota >= config.daily_quota:
                return JsonResponse({
                    'success': False,
                    'message': '今日API调用配额已用完'
                })
            
            # 调用腾讯地图API进行搜索
            search_results = self.search_places(config.api_key, keyword, location)
            
            if search_results:
                # 更新配额使用量
                config.used_quota += 1
                config.save()
                
                # 记录搜索历史
                MapSearchHistory.objects.create(
                    user=request.user,
                    search_keyword=keyword,
                    search_location=location,
                    result_count=len(search_results)
                )
                
                return JsonResponse({
                    'success': True,
                    'data': search_results,
                    'count': len(search_results)
                })
            else:
                return JsonResponse({
                    'success': False,
                    'message': '没有找到相关结果'
                })
                
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'搜索失败：{str(e)}'
            })
    
    def search_places(self, api_key, keyword, location='', search_type='region', radius=1000, page_size=20, page_index=1, get_subpois=0, filter_category=None):
        """
        调用腾讯地图API搜索地点
        严格按照腾讯地图官方文档实现(https://lbs.qq.com/service/placeSearch/placeSearchGuide/placeSearch)
        
        参数:
            api_key: 腾讯地图API密钥
            keyword: 搜索关键词(UTF-8编码，最长96字节)
            location: 位置参数，格式取决于search_type:
                - region: 城市名(如"北京")
                - nearby: 坐标(如"39.908823,116.397470")
                - rectangle: 矩形对角坐标(如"39.9075,116.3970;39.9100,116.4000")
            search_type: 搜索类型(region/nearby/rectangle)
            radius: 搜索半径(米)，仅nearby类型有效(10-1000米)
            page_size: 每页结果数(最大20)
            page_index: 页码
            get_subpois: 是否返回子地点(0/1)
            filter_category: 分类筛选(如"category=公交车站"或"category<>商务楼宇")
        """
        try:
            # 1. 参数验证
            if not keyword or len(keyword.encode('utf-8')) > 96:
                raise ValueError('搜索关键词无效或过长(最长96字节)')
            
            if search_type not in ['region', 'nearby', 'rectangle']:
                raise ValueError('不支持的搜索类型')
                
            if page_size > 20 or page_size < 1:
                page_size = 20
                
            if search_type == 'nearby' and (radius < 10 or radius > 1000):
                raise ValueError('搜索半径必须在10-1000米范围内')
                
            # 2. 构建基础参数
            params = {
                'key': api_key,
                'keyword': keyword,
                'page_size': page_size,
                'page_index': page_index,
                'get_subpois': get_subpois,
                'output': 'json'
            }
            
            # 3. 根据搜索类型设置边界参数
            if search_type == 'region':
                if not location:
                    location = '全国'
                # region格式: boundary=region(城市名,0)
                params['boundary'] = f'region({location},0)'
                
            elif search_type == 'nearby':
                if not location or ',' not in location:
                    raise ValueError('周边搜索需要有效的坐标参数')
                try:
                    # 验证坐标格式
                    lat, lng = [float(x.strip()) for x in location.split(',')]
                except ValueError:
                    raise ValueError('坐标格式无效，应为"纬度,经度"')
                
                # nearby格式: boundary=nearby(lat,lng,radius[,auto_extend])
                params['boundary'] = f'nearby({location},{radius},1)'  # 自动扩大范围
                
            elif search_type == 'rectangle':
                if not location or ';' not in location:
                    raise ValueError('矩形搜索需要两个对角坐标，格式为"lat1,lng1;lat2,lng2"')
                
                # 验证坐标格式
                try:
                    coords = location.split(';')
                    if len(coords) != 2:
                        raise ValueError('矩形搜索需要两个坐标点')
                    
                    for coord in coords:
                        lat, lng = [float(x.strip()) for x in coord.split(',')]
                except ValueError:
                    raise ValueError('坐标格式无效，应为"纬度,经度"')
                
                # rectangle格式: boundary=rectangle(lat1,lng1;lat2,lng2)
                params['boundary'] = f'rectangle({location})'
            
            # 4. 添加分类筛选
            if filter_category:
                # 支持: filter=category=分类名 或 filter=category<>分类名
                params['filter'] = filter_category
                
            # 5. 调试日志
            print(f"腾讯地图API请求参数: { {k: v for k, v in params.items() if k != 'key'} }")
            
            # 6. 调用API
            url = 'https://apis.map.qq.com/ws/place/v1/search'
            response = requests.get(url, params=params, timeout=15)
            result = response.json()
            
            # 7. 检查API状态
            status_code = result.get('status', -1)
            if status_code != 0:
                error_msg = result.get('message', '未知错误')
                if status_code == 310:
                    raise Exception('请求参数错误: ' + error_msg)
                elif status_code == 311:
                    raise Exception('Key格式错误')
                elif status_code == 306:
                    raise Exception('请求有护持信息请检查字符串')
                elif '配额' in error_msg:
                    raise Exception('API调用配额不足')
                else:
                    raise Exception(f'腾讯地图API错误({status_code}): {error_msg}')
                
            # 8. 处理结果
            places = []
            for item in result.get('data', []):
                place = {
                    'id': item.get('id'),
                    'title': item.get('title'),
                    'address': item.get('address'),
                    'tel': item.get('tel'),
                    'category': item.get('category'),
                    'type': item.get('type', 0),
                    'location': {
                        'lat': item.get('location', {}).get('lat'),
                        'lng': item.get('location', {}).get('lng')
                    },
                    'distance': item.get('_distance', 0),
                    'ad_info': {
                        'adcode': item.get('ad_info', {}).get('adcode'),
                        'province': item.get('ad_info', {}).get('province'),
                        'city': item.get('ad_info', {}).get('city'),
                        'district': item.get('ad_info', {}).get('district')
                    },
                    'sub_pois': [
                        {
                            'id': sub.get('id'),
                            'title': sub.get('title'),
                            'address': sub.get('address'),
                            'tel': sub.get('tel'),
                            'category': sub.get('category'),
                            'location': {
                                'lat': sub.get('location', {}).get('lat'),
                                'lng': sub.get('location', {}).get('lng')
                            }
                        } for sub in item.get('sub_pois', [])
                    ] if get_subpois else []
                }
                places.append(place)
                
            return {
                'status': status_code,
                'message': 'success',
                'count': result.get('count', 0),
                'data': places,
                'request_id': result.get('request_id')
            }
            
        except Exception as e:
            error_msg = f"搜索地点失败：{str(e)}"
            print(error_msg)
            return {
                'status': 500,
                'message': error_msg,
                'count': 0,
                'data': [],
                'request_id': None
            }


@method_decorator(csrf_exempt, name='dispatch')
class PublicMapSearchView(View):
    """
    公开的地图搜索API视图（无需登录）
    """
    
    def post(self, request):
        try:
            data = json.loads(request.body)
            keyword = data.get('keyword', '')
            location = data.get('location', '')
            
            if not keyword:
                return JsonResponse({
                    'success': False,
                    'message': '搜索关键词不能为空'
                })
            
            # 使用默认的腾讯地图API配置
            api_key = TENCENT_MAP_API_KEY  # 从配置文件中获取API密钥
            
            # 调用腾讯地图API进行搜索
            search_results = self.search_places(api_key, keyword, location)
            
            if search_results:
                return JsonResponse({
                    'success': True,
                    'data': search_results,
                    'count': len(search_results)
                })
            else:
                return JsonResponse({
                    'success': False,
                    'message': '没有找到相关结果'
                })
                
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'搜索失败：{str(e)}'
            })
    
    def search_places(self, api_key, keyword, location=''):
        """
        调用腾讯地图API搜索地点
        """
        try:
            # 腾讯地图地点搜索API
            url = 'https://apis.map.qq.com/ws/place/v1/search'
            params = {
                'keyword': keyword,
                'boundary': f'region({location},0)' if location else 'region(全国,0)',  # 如果未提供位置，默认搜索全国
                'page_size': 20,
                'page_index': 1,
                'key': api_key
            }
            
            # 设置referer头
            headers = {
                'Referer': 'http://localhost:8000'
            }
            
            response = requests.get(url, params=params, headers=headers, timeout=10)
            result = response.json()
            
            if result.get('status') == 0:
                places = []
                for item in result.get('data', []):
                    # 提取更完整的地点信息，包括行政区划信息
                    place = {
                        'id': item.get('id', ''),
                        'title': item.get('title', ''),
                        'address': item.get('address', ''),
                        'category': item.get('category', ''),
                        'location': {
                            'lat': item.get('location', {}).get('lat', 0),
                            'lng': item.get('location', {}).get('lng', 0)
                        },
                        'tel': item.get('tel', ''),
                        'type': item.get('type', 0),
                        'ad_info': item.get('ad_info', {}),  # 添加行政区划信息
                        'province': item.get('ad_info', {}).get('province', ''),
                        'city': item.get('ad_info', {}).get('city', ''),
                        'district': item.get('ad_info', {}).get('district', '')
                    }
                    places.append(place)
                return places
            else:
                print(f"API调用失败：{result.get('message')}")
                return []
                
        except Exception as e:
            print(f"搜索地点失败：{str(e)}")
            return []


@method_decorator(csrf_exempt, name='dispatch')
class MapRouteView(LoginRequiredMixin, View):
    """
    地图路线规划API视图
    """
    
    def post(self, request):
        try:
            data = json.loads(request.body)
            start_lat = data.get('start_lat')
            start_lng = data.get('start_lng')
            end_lat = data.get('end_lat')
            end_lng = data.get('end_lng')
            travel_mode = data.get('travel_mode', 'driving')
            
            if not all([start_lat, start_lng, end_lat, end_lng]):
                return JsonResponse({
                    'success': False,
                    'message': '起点和终点坐标不能为空'
                })
            
            # 获取激活的腾讯地图API配置
            config = TencentMapConfig.objects.filter(is_active=True).first()
            if not config:
                return JsonResponse({
                    'success': False,
                    'message': '没有激活的地图API配置'
                })
            
            # 检查配额
            config.reset_daily_quota()
            if config.used_quota >= config.daily_quota:
                return JsonResponse({
                    'success': False,
                    'message': '今日API调用配额已用完'
                })
            
            # 调用腾讯地图API进行路线规划
            route_result = self.plan_route(
                config.api_key, 
                start_lat, start_lng, 
                end_lat, end_lng, 
                travel_mode
            )
            
            if route_result:
                # 更新配额使用量
                config.used_quota += 1
                config.save()
                
                return JsonResponse({
                    'success': True,
                    'data': route_result
                })
            else:
                return JsonResponse({
                    'success': False,
                    'message': '路线规划失败'
                })
                
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'路线规划失败：{str(e)}'
            })
    
    def plan_route(self, api_key, start_lat, start_lng, end_lat, end_lng, travel_mode):
        """
        调用腾讯地图API进行路线规划
        """
        try:
            # 腾讯地图路线规划API - 修正URL格式，移除末尾斜杠
            url = 'https://apis.map.qq.com/ws/direction/v1/driving'
            if travel_mode == 'walking':
                url = 'https://apis.map.qq.com/ws/direction/v1/walking'
            elif travel_mode == 'transit':
                url = 'https://apis.map.qq.com/ws/direction/v1/transit'
            elif travel_mode == 'bicycling':
                url = 'https://apis.map.qq.com/ws/direction/v1/bicycling'
            
            params = {
                'from': f'{start_lat},{start_lng}',
                'to': f'{end_lat},{end_lng}',
                'key': api_key
            }
            
            # 设置referer头
            headers = {
                'Referer': 'http://localhost:8000'
            }
            
            response = requests.get(url, params=params, headers=headers, timeout=10)
            result = response.json()
            
            if result.get('status') == 0:
                route_data = result.get('result', {})
                routes = route_data.get('routes', [])
                
                if routes:
                    route = routes[0]  # 取第一条路线
                    return {
                        'distance': route.get('distance', 0),
                        'duration': route.get('duration', 0),
                        'polyline': route.get('polyline', []),
                        'steps': route.get('steps', []),
                        'start_location': {'lat': start_lat, 'lng': start_lng},
                        'end_location': {'lat': end_lat, 'lng': end_lng},
                        'travel_mode': travel_mode
                    }
            
            return None
                
        except Exception as e:
            print(f"路线规划失败：{str(e)}")
            return None


@login_required
def map_dashboard(request):
    """
    地图仪表板
    """
    context = {
        'total_locations': MapLocation.objects.filter(is_active=True).count(),
        'total_routes': MapRoute.objects.count(),
        'favorite_routes': MapRoute.objects.filter(is_favorite=True).count(),
        'recent_searches': MapSearchHistory.objects.filter(
            user=request.user
        ).order_by('-search_time')[:10],
        'location_categories': MapLocation.objects.filter(
            is_active=True
        ).values('category').distinct(),
    }
    return render(request, 'tencent_map/dashboard.html', context)


def get_shop_categories():
    """
    获取店铺分类列表
    """
    return [
        {'id': '050000', 'name': '餐饮'},
        {'id': '060000', 'name': '购物'},
        {'id': '070000', 'name': '生活服务'},
        {'id': '080000', 'name': '休闲娱乐'},
        {'id': '090000', 'name': '医疗健康'},
        {'id': '100000', 'name': '住宿'},
        {'id': '110000', 'name': '交通设施'},
        {'id': '120000', 'name': '金融'},
        {'id': '130000', 'name': '教育培训'},
        {'id': '140000', 'name': '政府机构'},
    ]

class MapShopsView(TemplateView):
    """
    地图店铺展示页面
    """
    template_name = 'tencent_map/map_shops.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['MAP_API_KEY'] = getattr(settings, 'TENCENT_MAP_API_KEY', '')
        context['categories'] = get_shop_categories()
        return context

    def get(self, request, *args, **kwargs):
        print("MapShopsView accessed")  # 调试信息
        return super().get(request, *args, **kwargs)

class ActivityListView(APIView):
    """
    活动位置列表API
    """
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        try:
            # 获取所有启用的活动位置
            locations = MapLocation.objects.filter(is_active=True).order_by('-created_at')
            
            # 使用序列化器
            serializer = MapLocationSerializer(locations, many=True)
            
            return Response({
                'success': True,
                'data': serializer.data,
                'count': len(serializer.data)
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({
                'success': False,
                'message': f'获取活动数据失败：{str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


def render_shop_list_partial(request):
    """
    渲染店铺列表部分模板
    """
    shops = []
    if request.GET.get('latitude') and request.GET.get('longitude'):
        # 如果有位置参数，调用周边搜索API
        response = requests.get(
            'https://apis.map.qq.com/ws/place/v1/search',
            params={
                'location': f"{request.GET['latitude']},{request.GET['longitude']}",
                'radius': request.GET.get('radius', 1000),
                'key': settings.TENCENT_MAP_API_KEY,
                'category': request.GET.get('category')
            }
        )
        shops = response.json().get('data', [])
    
    return render(request, 'tencent_map/_shop_list.html', {'shops': shops})

class NearbySearchView(APIView):
    """
    附近店铺搜索API（腾讯地图周边检索代理）
    """
    permission_classes = []
    
    def get(self, request):
        try:
            # 获取并验证参数
            latitude = request.GET.get('latitude')
            longitude = request.GET.get('longitude')
            
            if not latitude or not longitude:
                return Response({
                    'success': False,
                    'message': '缺少必要的参数：latitude, longitude'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            try:
                float(latitude)
                float(longitude)
            except ValueError:
                return Response({
                    'success': False,
                    'message': '无效的坐标参数'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            radius = request.GET.get('radius', '1000')  # 默认1000米
            keyword = request.GET.get('keyword', '店铺')  # 默认搜索店铺
            category = request.GET.get('category', '')  # 店铺分类
            
            # 获取激活的腾讯地图API配置
            config = TencentMapConfig.objects.filter(is_active=True).first()
            if not config:
                # 如果没有配置，使用默认的API Key
                api_key = TENCENT_MAP_API_KEY  # 从配置文件中获取API密钥
            else:
                api_key = config.api_key
            
            # 调用腾讯地图周边检索API
            search_results = self.search_nearby_shops(
                api_key, latitude, longitude, 
                radius, keyword, category
            )
            
            if search_results:
                return Response({
                    'success': True,
                    'data': search_results,
                    'count': len(search_results)
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    'success': False,
                    'message': '没有找到相关结果',
                    'data': [],
                    'count': 0
                }, status=status.HTTP_200_OK)
                
        except Exception as e:
            return Response({
                'success': False,
                'message': f'搜索附近店铺失败：{str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def search_nearby_shops(self, api_key, latitude, longitude, radius, keyword='店铺', category=''):
        """
        调用腾讯地图API搜索周边店铺
        文档: https://lbs.qq.com/service/webService/webServiceGuide/webServiceSearch
        """
        try:
            url = 'https://apis.map.qq.com/ws/place/v1/search'
            params = {
                'keyword': keyword,
                'boundary': f'nearby({latitude},{longitude},{radius})',  # 移除末尾的,1参数
                'page_size': 20,
                'page_index': 1,
                'key': api_key
            }
            
            # 添加分类筛选
            if category:
                params['filter'] = f'category={category}'
            
            # 添加调试信息
            print(f"腾讯地图API调用参数: { {k: v for k, v in params.items() if k != 'key'} }")
            
            # 设置请求头，包含referer信息
            headers = {
                'Referer': 'http://localhost:8000'  # 根据实际部署域名修改
            }
            
            response = requests.get(url, params=params, headers=headers, timeout=10)
            result = response.json()
            
            print(f"腾讯地图API响应状态: {result.get('status')}, 消息: {result.get('message')}")
            
            if result.get('status') == 0:
                shops = []
                for item in result.get('data', []):
                    shop = {
                        'id': item.get('id'),
                        'name': item.get('title'),
                        'address': item.get('address'),
                        'category': item.get('category'),
                        'location': {
                            'lat': item.get('location', {}).get('lat'),
                            'lng': item.get('location', {}).get('lng')
                        },
                        'distance': item.get('_distance', 0),
                        'tel': item.get('tel'),
                        'hours': item.get('opentime'),
                        'photos': [photo.get('url') for photo in item.get('photos', [])],
                        'rating': item.get('rating'),
                        'reviews': item.get('review_num'),
                        'tags': item.get('tag')
                    }
                    shops.append(shop)
                
                # 按距离排序
                shops.sort(key=lambda x: x['distance'])
                return shops
            else:
                error_msg = result.get('message', '未知错误')
                print(f"腾讯地图API调用失败({result.get('status')}): {error_msg}")
                return []
                
        except Exception as e:
            print(f"调用腾讯地图API失败：{str(e)}")
            return []

    @action(detail=False, methods=['GET'])
    def shop_categories(self, request):
        """
        获取店铺分类列表
        """
        categories = [
            {'id': '050000', 'name': '餐饮'},
            {'id': '060000', 'name': '购物'},
            {'id': '070000', 'name': '生活服务'},
            {'id': '080000', 'name': '休闲娱乐'},
            {'id': '090000', 'name': '医疗健康'},
            {'id': '100000', 'name': '住宿'},
            {'id': '110000', 'name': '交通设施'},
            {'id': '120000', 'name': '金融'},
            {'id': '130000', 'name': '教育培训'},
            {'id': '140000', 'name': '政府机构'},
        ]
        return Response(categories)

class ShopCategoriesView(APIView):
    """
    店铺分类API视图
    """
    def get(self, request):
        categories = get_shop_categories()
        return Response(categories)

def render_shop_list_partial(request):
    """
    渲染店铺列表部分模板
    """
    shops = []
    if request.GET.get('latitude') and request.GET.get('longitude'):
        # 如果有位置参数，调用周边搜索API
        response = requests.get(
            'https://apis.map.qq.com/ws/place/v1/search',
            params={
                'location': f"{request.GET['latitude']},{request.GET['longitude']}",
                'radius': request.GET.get('radius', 1000),
                'key': settings.TENCENT_MAP_API_KEY,
                'category': request.GET.get('category')
            }
        )
        shops = response.json().get('data', [])
    
    return render(request, 'tencent_map/_shop_list.html', {'shops': shops})
